package org.jinxing.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jinxing.dao.BooksCaseDAO;
import org.jinxing.dao.BooksClassfyDAO;
import org.jinxing.dao.BooksInfoDAO;
import org.jinxing.dao.BorrowsInfoDAO;
import org.jinxing.dao.RolesInfoDAO;
import org.jinxing.model.BooksCase;
import org.jinxing.model.BooksClassfy;
import org.jinxing.model.BooksClassfyExample;
import org.jinxing.model.BooksInfo;
import org.jinxing.model.BooksInfoExample;
import org.jinxing.model.BooksInfoExample.Criteria;
import org.jinxing.model.BorrowsInfo;
import org.jinxing.model.BorrowsInfoExample;
import org.jinxing.model.RolesInfo;
import org.jinxing.model.UsersInfo;
import org.jinxing.service.BooksService;
import org.jinxing.service.UsersInfoService;
import org.jinxing.utils.JsonUtils;
import org.jinxing.utils.ModelUtils;
import org.jinxing.utils.RequestUtils;
import org.jinxing.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/b")
public class BookController {
	protected static String className = BookController.class.getName();
	protected static Log logger = LogFactory.getLog(className);//日志对象
	@Autowired
	BooksInfoDAO booksInfoDAO;
	@Autowired
	BooksCaseDAO booksCaseDAO;
	@Autowired
	BooksClassfyDAO booksClassfyDAO;
	@Autowired
	RolesInfoDAO rolesInfoDAO;
	@Autowired
	BorrowsInfoDAO borrowsInfoDAO;
	@Autowired
	UsersInfoService usersInfoService;
	
	/**
	 * 进入用户管理首页
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request,HttpServletResponse response,Model model){
		logger.info("<|>"+className+"<|>index<|><|><|>");
		List<BooksCase> caseList = booksCaseDAO.selectByExample(null);
		
		BooksClassfyExample example = new BooksClassfyExample();
		example.createCriteria().andTypeEqualTo((byte)2);
		List<BooksClassfy> classfyList = booksClassfyDAO.selectByExample(example);
		
		model.addAttribute("caseList", JsonUtils.jsonFromObject(caseList));
		model.addAttribute("classfyList", JsonUtils.jsonFromObject(classfyList));
		return "/b/index";
	}
	
	/**
	 * 获取登录用户可见的用户信息组
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getBooks")
	public @ResponseBody String getBooks(HttpServletRequest request,HttpServletResponse response){
		logger.info("<|>"+className+"<|>getBooks<|><|><|>");
		int pageNo = RequestUtils.getInt(request, "page", 1);
		int pageSize = RequestUtils.getInt(request, "pagesize", 0);
		String bookName = request.getParameter("bookName");
		String validStr = request.getParameter("valid");
		
		BooksInfoExample example = new BooksInfoExample();
		if(pageSize > 0){
			example.setLimitClauseStart((pageNo-1)*pageSize);
			example.setLimitClauseCount(pageSize);
		}
		Criteria c = null;
		if(StringUtils.isNotBlank(bookName)){
			if(c == null){
				c = example.createCriteria();
			}
			c.andBooknameLike("%"+bookName+"%");
		}
		if(StringUtils.isNotBlank(validStr)){
			if(c == null){
				c = example.createCriteria();
			}
			c.andValidEqualTo(Integer.parseInt(validStr));
		}
		
		example.setOrderByClause(" id desc ");
		
		List<BooksInfo> list = booksInfoDAO.selectByExample(example);
		int count = booksInfoDAO.selectCountByExample(example);
		
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("Rows", list);
		result.put("Total", count);
		return JsonUtils.jsonFromObject(result);
	}
	
	@RequestMapping("/saveOrUpdate")
	public @ResponseBody String saveOrUpdate(HttpServletRequest request,HttpServletResponse response){
		String json = request.getParameter("json");
		Map<String,Object> result = new HashMap<String,Object>();
		List<Integer> successId = new LinkedList<Integer>();
		List tempList = JsonUtils.listFromJson(json);
		for(Object obj : tempList){
			BooksInfo book = ModelUtils.booksFromJson(JsonUtils.jsonFromObject(obj));
			if(null == book.getOperator()){
				book.setOperator(ServletUtils.getLgUser(request).getId());
			}
			if(null == book.getYear()){
				book.setYear(new Date());
			}
			
			if(null == book.getId()){
				Integer id = this.booksInfoDAO.insert(book);
				if(0 < id){
					successId.add(id);
				}
			}else{
				if(this.booksInfoDAO.updateByPrimaryKey(book) == 1){
					successId.add(book.getId());
				}
			}
		}
		result.put("sucessList", successId);
		logger.info("<|>"+className+"<|>saveOrUpdate<|><|>"+successId+"<|>");
		return JsonUtils.jsonFromObject(result);
	}
	
	@RequestMapping("/borrowIndex")
	public String borrowIndex(HttpServletRequest request,HttpServletResponse response,Model model){
		logger.info("<|>"+className+"<|>borrowIndex<|><|><|>");
		List<BooksCase> caseList = booksCaseDAO.selectByExample(null);
		
		BooksClassfyExample example = new BooksClassfyExample();
		example.createCriteria().andTypeEqualTo((byte)2);
		List<BooksClassfy> classfyList = booksClassfyDAO.selectByExample(example);
		
		model.addAttribute("caseList", JsonUtils.jsonFromObject(caseList));
		model.addAttribute("classfyList", JsonUtils.jsonFromObject(classfyList));
		UsersInfo user = ServletUtils.getLgUser(request);
		model.addAttribute("availNum",availNum(user.getId()));
		
		return "/b/borrowIndex";
	}
	
	@RequestMapping("/borrowedIndex")
	public String borrowedIndex(HttpServletRequest request,HttpServletResponse response,Model model){
		logger.info("<|>"+className+"<|>borrowedIndex<|><|><|>");
		List<BooksCase> caseList = booksCaseDAO.selectByExample(null);
		
		BooksClassfyExample example = new BooksClassfyExample();
		example.createCriteria().andTypeEqualTo((byte)2);
		List<BooksClassfy> classfyList = booksClassfyDAO.selectByExample(example);
		
		model.addAttribute("caseList", JsonUtils.jsonFromObject(caseList));
		model.addAttribute("classfyList", JsonUtils.jsonFromObject(classfyList));
		return "/b/borrowedIndex";
	}
	
	protected int availNum(Integer userId){
		int allNum = this.usersInfoService.getById(userId).getMaxnum();
		BorrowsInfoExample borrowsInfoExample = new BorrowsInfoExample();
		BorrowsInfoExample.Criteria borrowsC = borrowsInfoExample.createCriteria();
		borrowsC.andBorrowerEqualTo(userId);
		borrowsC.andIsbackEqualTo(0);//未归还书籍
		int availNum = allNum - this.borrowsInfoDAO.selectCountByExample(borrowsInfoExample);
		return availNum;
	}
	
	@RequestMapping("/saveBorrow")
	public @ResponseBody String saveBorrow(HttpServletRequest request,HttpServletResponse response){
		
		int type = RequestUtils.getInt(request, "type", 0);
		int userId = 0;
		int bookId =RequestUtils.getInt(request, "bid", 0);
		UsersInfo lgUser = ServletUtils.getLgUser(request);
		int result = 0;
		if(type == 0){//自借
			userId = lgUser.getId();
		}else{
			userId = RequestUtils.getInt(request, "uid", 0);
			if(0 == userId){
				return "-1";
			}
		}
		if(availNum(userId) > 0){
			BorrowsInfo borrowsInfo = new BorrowsInfo();
			borrowsInfo.setBookid(bookId);
			borrowsInfo.setBorrower(userId);
			borrowsInfo.setBorrowoperator(lgUser.getId());
			borrowsInfo.setBorrowtime(new Date());
			borrowsInfo.setIsback(0);
			Date date = new Date();
			date.setDate(date.getDate()+30);
			borrowsInfo.setPlantime(date);
			result = this.borrowsInfoDAO.insert(borrowsInfo);
			if(result<=0){
				return "-3";
			}else{
				BooksInfo book = new BooksInfo();
				book.setId(bookId);
				book.setValid(1);
				this.booksInfoDAO.updateByPrimaryKeySelective(book);
			}
		}else{
			return "-2";
		}
		
		logger.info("<|>"+className+"<|>saveBorrow<|><|>"+result+"<|>");
		return "0";
	}
	
}
